package com.zl.learning.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

public class TestBlockQueue2 {

    private static final BlockingQueue<String> QUEUE = new LinkedBlockingDeque<>();
    private static volatile boolean start = true;

    public static void main(String[] args) {
        TestBlockQueue2 testBlockQueue = new TestBlockQueue2();
        final Thread thread = new Thread(testBlockQueue::run);
        thread.start();
        Scanner scanner = new Scanner(System.in);
        String val = scanner.nextLine();
        while (!"exit".equals(val)) {
            String[] vv = val.split(",");
            QUEUE.addAll(Arrays.asList(vv));
            val = scanner.nextLine();
        }
        thread.interrupt();
    }

    private void run() {
        List<String> list = new ArrayList<>();
        while (start) {
            try {
                String val = "";
                if (QUEUE.isEmpty()) {
                    val = QUEUE.take();
                    list.add(val);
                }
                while (QUEUE.size() > 0) {
                    val = QUEUE.poll();
                    list.add(val);
                }
                while (list.size() > 0 && QUEUE.isEmpty()) {
                    list.forEach(r -> System.out.print(r + "---"));
                    System.out.println();
                    list.remove(0);
                    TimeUnit.SECONDS.sleep(5);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
                start = false;
            }
        }
    }

}
